using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoroutineQueue
{
	private readonly uint _maxActive;

	private readonly Func<IEnumerator, Coroutine> _coroutineStarter;

	private readonly Queue<IEnumerator> _queue;

	private uint _numActive;

	public CoroutineQueue(uint maxActive, Func<IEnumerator, Coroutine> coroutineStarter)
	{
		if (maxActive == 0)
		{
			throw new ArgumentException("Must be at least one", "maxActive");
		}
		_maxActive = maxActive;
		_coroutineStarter = coroutineStarter;
		_queue = new Queue<IEnumerator>();
	}

	public void Run(IEnumerator coroutine)
	{
		if (_numActive < _maxActive)
		{
			IEnumerator arg = CoroutineRunner(coroutine);
			_coroutineStarter(arg);
		}
		else
		{
			_queue.Enqueue(coroutine);
		}
	}

	private IEnumerator CoroutineRunner(IEnumerator coroutine)
	{
		_numActive++;
		while (coroutine.MoveNext())
		{
			yield return coroutine.Current;
		}
		_numActive--;
		if (_queue.Count > 0)
		{
			IEnumerator coroutine2 = _queue.Dequeue();
			Run(coroutine2);
		}
	}
}
